package com.sram.dao.impl;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.net.SyslogAppender;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.sram.dao.UserDao;
import com.sram.entity.User;
public class UserDaoImpl implements UserDao {
	private HibernateTemplate template;
	public HibernateTemplate getTemplate() {
		return template;
	}
	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}
	@Override
	public void addUser(User user) {
		template.save(user);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<User> findUser(DetachedCriteria detachedCriteria) {
		return template.findByCriteria(detachedCriteria);
	}
	
	@Override
	public void deleteUser(int id) {
		User user = (User) template.get(User.class, id);
		template.delete(user);
	}
	@Override
	public User getUserByUserNameAndPassword(final String userName, final String password) {
		try {
			@SuppressWarnings("unchecked")
			List<User> users = template.find("from User u where u.userName=? and u.password=?", new Object[]{userName,password});
		
			if(users != null && users.size() >= 1){
				System.out.println("------============");
				return users.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}				
		return null;
	}
	@Override
	public void updateUser(User user) {
		template.update(user);
	}
	@Override
	public User getUserByUserName(String userName) {
		try {
		
			System.out.println("1111111111111111111111111");
			List<User> users = template.find("from User u where u.userName=?", new Object[]{userName});
		
			if(users != null && users.size() >= 1){
				System.out.println("------============");
				return users.get(0);
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public List<User> findall() {
		List<User> users = template.find("from User u");
		return users;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<User> pageQuery(DetachedCriteria detachedCriteria, int firstResult, int pageSize) {
		// TODO Auto-generated method stub
		return this.getTemplate().findByCriteria(detachedCriteria, firstResult, pageSize);
	}
}
